<template>
  <div>
    <el-card>
      <div class="list-h">
        <div>
          <el-button
            v-auth="`/project/change-change`"
            type="primary"
            class="add-option"
            @click="state.changeDialogFormVisible = true"
            >申请变更</el-button
          >
          <el-button
            v-auth="`/project/change-stop`"
            type="primary"
            class="add-option"
            @click="state.stopDialogFormVisible = true"
            >申请终止</el-button
          >
        </div>
        <el-form
          :inline="true"
          :model="formInline"
          ref="formRef"
          @submit.prevent
          class="demo-form-inline"
        >
          <el-form-item label="单据编号" prop="alterNumLike">
            <el-input
              class="width-custom120"
              clearable
              v-model="formInline.alterNumLike"
            />
          </el-form-item>
          <el-form-item label="变更名称" prop="alterNameLike">
            <el-input
              class="width-custom120"
              clearable
              v-model="formInline.alterNameLike"
            />
          </el-form-item>
          <el-form-item label="项目名称" prop="projectManageId">
            <el-select
              class="width-custom120"
              v-model="formInline.projectManageId"
              filterable
              clearable
              remote
              placeholder="请输入名称搜索"
              :remote-method="getTableData"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="申请人" prop="createUserNameLike">
            <el-input
              clearable
              class="width-custom120"
              v-model="formInline.createUserNameLike"
            />
          </el-form-item>
          <el-form-item label="申请时间" prop="">
            <el-date-picker
              clearable
              class="width-custom220"
              v-model="timeValue"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD"
              @change="handleChangeDate"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-skeleton style="height: 50vh" :rows="8" :loading="loading" animated>
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        >
          <template #empty>
            <el-empty :image-size="150" description="暂无数据"></el-empty>
          </template>
          <el-table-column type="index" label="序号">
            <template v-slot="scope">
              <span>{{
                (pageState.pageNum - 1) * pageState.pageSize + scope.$index + 1
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="alterNum" label="单据编号" width="170">
          </el-table-column>
          <el-table-column prop="alterName" label="变更名称"> </el-table-column>
          <el-table-column
            prop="alterationReason"
            label="变更/终止理由或原因"
            show-overflow-tooltip
            min-width="140"
          >
          </el-table-column>
          <el-table-column prop="projectName" label="所属项目">
          </el-table-column>
          <el-table-column prop="createUserName" label="申请人">
          </el-table-column>
          <el-table-column prop="createTime" label="申请时间" width="140">
          </el-table-column>
          <el-table-column label="审批状态">
            <template #default="{ row }">
              {{ row.applyStatus === "3" ? "已结束" : "审核中" }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="alterationTypeName" label="变更类型">
          </el-table-column> -->
          <!-- <el-table-column label="当前审批节点" :min-width="100">
            <template #default="{ row }">{{
              row.nodeStatusName || "信息填报"
            }}</template>
          </el-table-column>
          <el-table-column
            prop="curHandleUserName"
            label="当前处理人"
            width="120"
          ></el-table-column> -->

          <el-table-column fixed="right" label="操作" width="100">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="handleLook(row)"
                >查看</el-button
              >
              <!-- <el-button
                type="text"
                @click="handleEdit(row, 'approval')"
                v-if="
                  row.isHandler === 1 &&
                  (row.curNodeId || row.nodeStatusYsCode) != 'end'
                "
                >审批</el-button
              > -->
            </template>
          </el-table-column>
        </el-table>
        <re-pagination
          v-if="total > 0"
          :total="total"
          v-model:page="pageState.pageNum"
          v-model:limit="pageState.pageSize"
          @pagination="handleChangePage"
        />
      </el-skeleton>
    </el-card>
  </div>
  <el-dialog
    :show-close="false"
    title="变更信息"
    v-model="state.changeDialogFormVisible"
    destroy-on-close
    width="45vw"
  >
    <changeDialog
      @cancel="state.changeDialogFormVisible = false"
      @submit="submitChange"
    />
  </el-dialog>
  <el-dialog
    title="终止申请"
    v-model="state.stopDialogFormVisible"
    destroy-on-close
    width="45vw"
  >
    <stopDialog
      @cancel="state.stopDialogFormVisible = false"
      @submit="submitStop"
    />
  </el-dialog>

  <approveDialog
    v-if="approveDialogVisiable"
    :nodeId="nodeId"
    :flowType="state.flowType"
    @cancel="approveDialogVisiable = false"
    @sure="sureSubmit"
  ></approveDialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from "vue";
import { useRouter } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import stopDialog from "../manage/components/stopDialog.vue";
import changeDialog from "../manage/components/changeDialog.vue";
import * as api from "/@/api/change";
import { flowStart, postProjecStop, postProjectList } from "/@/api/project";
import { postDictList } from "/@/api/common";
import { useProjectStoreHook } from "/@/store/modules/project";
import { flowTypeCode } from "../create/types";
import approveDialog from "/@/components/approveDialog/index.vue";
let approveDialogVisiable = ref<boolean>(false); // 点击提交弹窗，选择下一步审批人
const nodeId = "ACT_010";
const initData = {
  // TODO 接口未出，后续根据字段直接替换
  alterNumLike: "", // 单据编号
  alterNameLike: "", // 变更名称
  projectManageId: "", // 项目名称
  createUserNameLike: "", // 申请人
  // alterationTypeCode: "", // 变更类型
  createTimeStrStart: "",
  createTimeStrEnd: ""
};
let state = reactive({
  flowType: "",
  changeDialogFormVisible: false,
  stopDialogFormVisible: false,
  changeInfo: null,
  stopInfo: null
});

let timeValue = ref(null);
const router = useRouter();

const formInline = reactive(initData);
const pageState = reactive({
  pageNum: 1,
  pageSize: 10
});

let projectList = ref([]);
let flowStatusArr = ref([]);

const formRef = ref<HTMLFormElement | null>(null) as any;
const tableData = ref([]);
let loading = ref<boolean>(false);
let total = ref<number>(0);
const formParams = ref<typeof initData>({ ...initData });

const submitChange = changeInfo => {
  let storeAuth = useProjectStoreHook();
  storeAuth.setChangeInfo(changeInfo);
  state.changeInfo = changeInfo;
  state.changeDialogFormVisible = false;

  const cantype =
    changeInfo.projectObj.canProcess === 1 &&
    changeInfo.projectObj.saveStatus === "3"
      ? 1
      : 2;
  router.push({
    path: "/project/create",
    query: { id: changeInfo.projectId, mode: "change", cantype }
  });
};

const sureSubmit = async params => {
  approveDialogVisiable.value = false;
  const projectChangeParamDTO = Object.assign({}, state.stopInfo);
  const { code, data } = await postProjecStop({
    id: state.stopInfo.projectId,
    reason: "",
    projectChangeParamDTO
  });
  if (code === 200) {
    const submitParams = {
      formBaseInfo: {
        billName: `${state.stopInfo.projectObj.projectName}终止审批`,
        projectName: state.stopInfo.projectObj.projectName,
        projectManageId: state.stopInfo.projectObj.id,
        id: data,
        flowStartAttachmentArr: []
      },
      flowFormData: {
        businessId: data,
        flowTypeCode: state.flowType,
        projectManageId: state.stopInfo.projectObj.id,
        remarks: params.remark,
        saveState: "1"
      },
      formSubMap: {
        stageStatus: "22",
        flowType: state.flowType,
        assignee: params?.handlederId?.id,
        opinion: ``
      }
      // startProcess(submitParams);
    };
    const { code, message } = await flowStart(submitParams);
    if (code === 200) {
      NotifMessage.success(message);
    } else {
      NotifMessage.error(message);
    }
  }
};

const submitStop = async stopInfo => {
  let storeAuth = useProjectStoreHook();
  storeAuth.setStop(stopInfo);
  state.stopInfo = stopInfo;
  const emyp =
    stopInfo.projectObj.approveTypeMaxCode +
    "," +
    stopInfo.projectObj.approveTypeMinCode;
  state.flowType = flowTypeCode[emyp];
  state.stopDialogFormVisible = false;
  approveDialogVisiable.value = true;
};

const getTableList = async (obj: object = {}) => {
  try {
    loading.value = true;
    const { code, data } = await api.postAlterationList({
      ...obj,
      ...pageState
    });
    if (code === 200) {
      tableData.value = data.list;
      total.value = data.rows;
    }
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
};

const handleReset = () => {
  formRef.value.resetFields();
  timeValue.value = null;
  handleChangeDate(null);
  pageState.pageNum = 1;
  formParams.value = initData;
  getTableList(formInline);
};

const handleSearch = () => {
  pageState.pageNum = 1;
  formParams.value = formInline;
  getTableList(formInline);
};

const handleChangePage = () => {
  getTableList(formParams.value);
};

// const handleAdd = () => {
//   router.replace({
//     path: "/project/change/detail",
//     query: { mode: "add" }
//   });
// };

// const handleEdit = row => {
//   const { id } = row;
//   router.replace({
//     path: "/project/change/detail",
//     query: {
//       id,
//       mode: "edit"
//     }
//   });
// };

watch(
  () => formInline.projectManageId,
  newVal => {
    if (!newVal) {
      projectList.value = [];
    }
  }
);

async function getTableData(query = "") {
  if (!query) {
    projectList.value = [];
    return;
  }
  try {
    const params = {
      isFilings: "1",
      pageNum: 1,
      pageSize: 100,
      projectNameLike: query
    };
    const { code, data } = await postProjectList(params);
    if (code === 200) {
      projectList.value = data.list.map(item => {
        return { id: item.id, projectName: item.projectName };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

const handleLook = row => {
  const { id } = row;
  const mode = row.alterName.indexOf("变更") !== -1 ? "change" : "stop";
  router.replace({
    path: "/project/change/detail",
    query: {
      id,
      flowId: row.flowId,
      taskId: row.curTaskId,
      instanceId: row.instanceId,
      nodeId: row.nodeStatusCode && row.nodeStatusCode.toLocaleUpperCase(),
      approvalTypeCode: row.approvalTypeCode,
      isSkipAlter: row.isSkipAlter,
      applyStatus: row.applyStatus,
      mode
    }
  });
};

// const handleEdit = (row, type) => {
//   const { id } = row;
//   router.replace({
//     path: "/project/change/detail",
//     query: {
//       id,
//       flowId: row.flowId,
//       taskId: row.curTaskId,
//       instanceId: row.instanceId,
//       nodeId: row.nodeStatusCode && row.nodeStatusCode.toLocaleUpperCase(),
//       approvalTypeCode: row.approvalTypeCode,
//       isSkipAlter: row.isSkipAlter,
//       mode: type
//     }
//   });
// };

// const handleApprove = async row => {
//   const { id } = row;
//   const params = {
//     id,
//     applyStatus: "2"
//   };
//   const { code, message } = await api.postAlterationApprove(params);
//   console.log(code, message);
//   if (code === 200) {
//     NotifMessage.success(message);
//     getTableList(formParams.value);
//   } else {
//     NotifMessage.error(message);
//   }
// };

// const handleDelete = async row => {
//   try {
//     const { code, message } = await api.postAlterationDelete({
//       id: row.id
//     });
//     if (code === 200) {
//       NotifMessage.success("删除成功");
//       getTableList(formParams.value);
//     } else {
//       NotifMessage.error(message);
//     }
//   } catch (err) {
//     console.log(err);
//   }
// };

const handleChangeDate = item => {
  console.log(item, "date");
  if (item) {
    formInline.createTimeStrStart = item[0];
    formInline.createTimeStrEnd = item[1];
  } else {
    formInline.createTimeStrStart = "";
    formInline.createTimeStrEnd = "";
  }
};

// 变更类型
// const initChangeTypeList = async () => {
//   try {
//     const params = {
//       dicType: "flow_alteration_type"
//     };
//     const { code, data } = await postDictList(params);
//     changeTypeList.value = data;
//     console.log(code, data);
//   } catch (err) {
//     console.log(err);
//   }
// };

// initChangeTypeList();

// 审批状态
const initFlowStatusList = async () => {
  try {
    const params = {
      dicType: "rd_flow_status"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      flowStatusArr.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

getTableList(formInline);
initFlowStatusList();
</script>
<style scoped lang="scss">
.redColor {
  width: 10px;
  height: 10px;
  background: #f5a623;
  border-radius: 50%;
  display: inline-block;
}

.greenColor {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #21d371;
  display: inline-block;
}

.grayColor {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #979797;
  display: inline-block;
}
</style>
